package com.gzx.plugin.tjzy.modular.sse.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.gzx.plugin.tjzy.modular.call.ht.entity.GzxHtVoiceText;
import com.gzx.plugin.tjzy.modular.call.scripts.config.CallScriptInitializationConfig;
import com.gzx.plugin.tjzy.modular.qianwen.service.IntentPromptService;
import com.gzx.plugin.tjzy.modular.sse.service.GzxSseService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.sses.consts.SseMsgTypeConstant;
import vip.xiaonuo.common.sses.entity.SseMessage;
import vip.xiaonuo.common.sses.util.CommonSseUtil;
import vip.xiaonuo.common.util.CommonDateUtil;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author zjt
 * @description
 * @date 2025/4/29 17:41
 */
@Service
@RequiredArgsConstructor
public class GzxSseServiceImpl implements GzxSseService {

    private final CommonSseUtil commonSseUtil;

    private final IntentPromptService intentPromptService;

    private final CallScriptInitializationConfig callScriptInitializationConfig;

    /**
     * 初始化SSE连接
     *
     * @param clientId
     */
    @Override
    public SseEmitter initSse(String clientId) {
        return commonSseUtil.createConnection(clientId, StpLoginUserUtil.getLoginUser().getId());
    }

    /**
     * 发送消息
     */
    @Override
    public void sendMessage() {
        GzxHtVoiceText htVoiceText = new GzxHtVoiceText();
        htVoiceText.setChatTime(CommonDateUtil.getCurrentTimeStr());
        int random = (int) (Math.random() * 2) + 1;
        htVoiceText.setSpeakerRole(random);
        htVoiceText.setCallId("20250218111641012934400277");
        String text = generateRandomChineseString((int) (Math.random() * 10));
        if (random == 1) {
            htVoiceText.setContent("我是客户:" + getKeyword() + "我就不想还钱");
        }
        if (random == 2) {
            htVoiceText.setContent("我是坐席:" + text);
        }
        commonSseUtil.sendMessageToUser(StpLoginUserUtil.getLoginUser().getId(), new SseMessage(SseMsgTypeConstant.VOICE_TEXT, JSON.toJSONString(htVoiceText)));
        if (htVoiceText.getSpeakerRole() == 1) {
            //获取推荐话术
            List<String> callScriptsList = getCallScripts(htVoiceText.getContent());
            if (CollectionUtil.isNotEmpty(callScriptsList)) {
                commonSseUtil.sendMessageToUser(StpLoginUserUtil.getLoginUser().getId(), new SseMessage(SseMsgTypeConstant.CALL_SCRIPTS, JSON.toJSONString(Map.of(htVoiceText.getChatTime(), callScriptsList))));
            }
        }
    }

    /**
     * 给所有人发通知
     *
     * @param type
     * @param msg
     */
    @Override
    public void sendAll(String type, String msg) {
        commonSseUtil.sendMessageToAll(new SseMessage(type, msg));
    }

    private String generateRandomChineseString(int length) {
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int codePoint = 0x4E00 + random.nextInt(0x9FA5 - 0x4E00 + 1);
            sb.append(Character.toChars(codePoint));
        }
        return sb.toString();
    }

    private String getKeyword() {
        String[] array = {" ", "跳楼", "跳河", "喝药", "不想活"};
        // 创建Random对象
        Random random = new Random();
        // 生成一个随机索引
        int randomIndex = random.nextInt(array.length);
        return array[randomIndex];
    }

    private List<String> getCallScripts(String voiceText) {
        String intent = intentPromptService.analyzeIntent(voiceText);
        return StringUtils.isNotBlank(intent) ? callScriptInitializationConfig.getCallScriptMap(intent) : List.of();
    }
}
